//
//  VVSportMapViewController.m
//  DingDingSport
//
//  Created by 王惠平 on 2017/4/21.
//  Copyright © 2017年 will wang. All rights reserved.
//

#import "VVSportMapViewController.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import "VVSportTrack.h"

@interface VVSportMapViewController ()<MAMapViewDelegate>

//运动轨迹
//@property (nonatomic, strong) VVSportTrack *track;

//记录是否添加起点大头针
@property (nonatomic, assign) BOOL hasSetStartAnno;

@end

@implementation VVSportMapViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //初始化地图
    _mapView = [[MAMapView alloc]initWithFrame:self.view.bounds];
    
    //把视图添加到view
    [self.view addSubview:_mapView];
    
    [self setupMapView];
    
    //self.track = [VVSportTrack new];
}

- (void)setupMapView {
    
    
    //隐藏标尺
    _mapView.showsScale = NO;
    
    //关闭3D效果
    _mapView.rotateCameraEnabled = NO;
    
    ///如果您需要进入地图就显示定位小蓝点，则需要下面两行代码
    _mapView.showsUserLocation = YES;
    _mapView.userTrackingMode = MAUserTrackingModeFollow;

    //后台运行  注意设置backgroundmode
    _mapView.allowsBackgroundLocationUpdates = YES;
    
    //取消自动暂停
    _mapView.pausesLocationUpdatesAutomatically = NO;
    
    _mapView.delegate = self;
    
}

- (void)viewDidLayoutSubviews {
    
    [super viewDidLayoutSubviews];
    
    //使用其他视图传递的视图尺寸时,需要注意在子视图布局完成后进行
    //设置指南针位置 要求指南针中心点和轨迹按钮的中心点保持一致
    //轨迹视图 - 地图中compass(指南针)的宽高* 0.5
    _mapView.compassOrigin = CGPointMake(_trackBtnCenter.x - _mapView.compassSize.width * 0.5, _trackBtnCenter.y - _mapView.compassSize.height * 0.5);
}

//重新set方法
- (void)setMapType:(VVMapType)mapType {

    _mapType = mapType;
    
    //设置地图类型
    _mapView.mapType = (MAMapType)_mapType;
    
}

//代理方法

/**
 点击地图时调用

 @param mapView 地图
 @param coordinate 点击位置的经纬度
 */
//- (void)mapView:(MAMapView *)mapView didSingleTappedAtCoordinate:(CLLocationCoordinate2D)coordinate {
//    
//    //构造折线数据对象
//    CLLocationCoordinate2D commonPolyLineCoords[2];
//    
//    //定位点
//    commonPolyLineCoords[0].latitude = self.mapView.userLocation.coordinate.latitude;
//    commonPolyLineCoords[0].longitude = self.mapView.userLocation.coordinate.longitude;
//    
//    //点击点
//    commonPolyLineCoords[1].latitude = coordinate.latitude;
//    commonPolyLineCoords[1].longitude = coordinate.longitude;
//    
//    //构造折线对象
//    MAPolyline *commonPolyLine = [MAPolyline polylineWithCoordinates:commonPolyLineCoords count:2];
//    
//    //在地图上添加折线对象
//    [_mapView addOverlay:commonPolyLine];
//    
//    
//}

- (void)mapView:(MAMapView *)mapView didFailToLocateUserWithError:(NSError *)error {
    //GPS断开
    //发送GPS跟新的通知
    [[NSNotificationCenter defaultCenter] postNotificationName:@"VVSportGPSStateDidChangeNote" object:nil userInfo:@{@"VVSportGPSStateDidChangeNoteGPSStateKey":@(VVSportGPSStateDisconnect)}];
    
}

- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation {
    
    //过滤掉方向改变触发更新事件
    if (updatingLocation == NO) {
        
        return;
    }
    
#warning //位置更新后,发送通知给控制器 使用通知因为多个界面使用数据
    [[NSNotificationCenter defaultCenter] postNotificationName:@"VVSportLocationDidUpdateNote" object:nil userInfo:@{@"VVSportLocationDidUpdateNoteLocationKey": userLocation.location}];
    
    //更新位置后,设置地图中心点
    _mapView.centerCoordinate = userLocation.location.coordinate;
    
    //添加大头针
    if (_hasSetStartAnno == NO && self.track.startAnno) {
        
        [_mapView addAnnotation:self.track.startAnno];
        _hasSetStartAnno = YES;

    }
    
    VVSportPolyline *newPolyline = [self.track appendPolylineWithDestCoord:userLocation.location];
    
    //添加折线
    [_mapView addOverlay:newPolyline];
    
    //NSLog(@"总距离:%f, 总时长:%f, 最大速度:%f, 平均速度:%f", self.track.totalDistance, self.track.totalTime, self.track.maxSpeed, self.track.avgSpeed);

    
}

//设置大头针视图时调用
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *reuseIndetifier = @"annotationReuseIndetifier";
        MAAnnotationView *annotationView = (MAAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIndetifier];
        }
        //annotationView.image = [UIImage imageNamed:@"map_annotation_bike"];
        
        //设置图片
        annotationView.image = [UIImage imageNamed:self.track.sportTypeImageName];

        
        //设置中心点偏移，使得标注底部中间点成为经纬度对应点
        annotationView.centerOffset = CGPointMake(0, -annotationView.image.size.height * 0.5);
        return annotationView;
    }
    return nil;
}


- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id <MAOverlay>)overlay
{
    if ([overlay isKindOfClass:[VVSportPolyline class]])
    {
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:overlay];
        //线宽
        polylineRenderer.lineWidth    = 4.f;
        
        VVSportPolyline *polyline = overlay;
       
        //描边颜色
        polylineRenderer.strokeColor  =polyline.strokeColor;
        
        //拐点样式
        polylineRenderer.lineJoinType = kMALineJoinRound;
       
        //头尾样式
        polylineRenderer.lineCapType  = kMALineCapRound;
        
        return polylineRenderer;
    }
    
    return nil;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
